<script setup>
import {reactive} from 'vue';
import {useRouter} from 'vue-router';
import axios from 'axios';
import moment from 'moment';

import {
  ElContainer,
  ElHeader,
  ElMain,
  ElFooter,
  ElForm,
  ElFormItem,
  ElInput,
  ElRadioGroup,
  ElRadio,
  ElDatePicker,
  ElButton,
  ElMessage
} from 'element-plus';

// 获得 router 实例(用于实现编程式导航)
const router = useRouter();

const form = reactive({
  email: '',
  tel: '',
  password: '',
  confirm: '',
  birthdate: '',
  married: ''
});

function validate() {
  // 对用户输入的数据进行校验

  return true;
}

function register() {
  if( validate() ) {
    let entity = {...form};
    entity.birthdate = moment(entity.birthdate).format('YYYY-MM-DD');
    delete entity.confirm;
    axios.post('/backapi/customer/register', entity )
        .then( resp => {
          const { success, message } = resp.data;
          if( success ) {
            router.push('/login');
            return;
          }
          ElMessage({type:'warning', message});
        }).catch( reason => {
          if( reason instanceof Error ) {
            ElMessage.error('添加失败');
          }
        })
  }
}

</script>

<template>
  <el-container>
    <el-header>
      <h3>注册新用户</h3>
    </el-header>
    <el-main>
      <el-form :model="form" label-width="200px">
        <el-form-item label="邮箱">
          <el-input v-model="form.email"/>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="form.tel"/>
        </el-form-item>
        <el-form-item label="密码">
          <el-input type="password" v-model="form.password"/>
        </el-form-item>
        <el-form-item label="确认密码">
          <el-input type="password" v-model="form.confirm"/>
        </el-form-item>
        <el-form-item label="出生日期">
          <el-date-picker v-model="form.birthdate"/>
        </el-form-item>
        <el-form-item label="婚姻状况">
          <el-radio-group v-model="form.married">
            <el-radio label="Y">已婚</el-radio>
            <el-radio label="N">单身</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="">
          <el-button type="primary" @click="register">注册</el-button>
        </el-form-item>
      </el-form>
    </el-main>
    <el-footer>
      已有账号？前去<a href="/login">登录</a>
    </el-footer>
  </el-container>
</template>

<style scoped>

</style>